package com.ls.herostory.cmdhandler;

import com.ls.herostory.util.BeanUtils;
import com.ls.herostory.util.ClassScanner;
import com.ls.herostory.util.InterfaceClassFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/12 11:21
 * @since
 */
public class CmdHandlerFactory {

    private final static Logger logger = LoggerFactory.getLogger(CmdHandlerFactory.class);

    private static Map<Type, CmdHandler> map = new HashMap<>();

    static {
        init();
    }

    /**
     *
     */
    public static void init(){
        // 扫描接口CmdHandler的实现类
        ClassScanner classScanner = new ClassScanner(new InterfaceClassFilter(CmdHandler.class));
        List<Class> classes = classScanner.scan("");

        // 注册
        for (Class clazz : classes) {
            // 获取泛型参数
            Type[] interfaceArg = BeanUtils.getInterfaceArgs(clazz, CmdHandler.class);
            // 实例化
            CmdHandler cmdHandler = (CmdHandler) BeanUtils.instance(clazz);

            // 注册
            map.put(interfaceArg[0], cmdHandler);
            logger.info("register cmdhandler type: {}, cmdhandler class: {}", interfaceArg[0], clazz.getName());
        }
    }

    public static CmdHandler getHandler(Class<?> cmdClass){
        return map.get(cmdClass);
    }


}
